<template>
  <div class="account-container">
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="left">
        <div class="left-item">
          <el-form-item label="账号" class="el-form-item">
            <el-input v-model="filterForm.phone" maxlength="11" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="授权名称" class="el-form-item">
            <el-input v-model="filterForm.username" placeholder="请输入授权名称" />
          </el-form-item>
          <el-form-item label="合作属性" class="el-form-item">
            <el-select v-model="filterForm.roleId" placeholder="全部" style="width: 120px">
              <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item class="Operation">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="right">
        <el-button type="primary" @click="handleAdd" v-if="mainStore.userInfo.role?.roleType >= 90">添加账号</el-button>
        <el-button type="primary" @click="handleDowlist">导出账号列表</el-button>
      </div>
    </div>

    <el-table :data="tableData" border class="el-table">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="phone" label="账号" width="250" />
      <el-table-column prop="username" label="授权名称" width="480" />
      <el-table-column prop="role.name" label="合作属性" width="260" />

      <el-table-column label="考级模块" width="130">
        <template #default="scope">
          <el-tag :type="scope.row.examEnabled ? 'success' : 'info'">
            {{ scope.row.examEnabled ? '开启' : '关闭' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="展演模块" min-width="15%">
          <template #default="scope">
            <el-tag :type="scope.row.showEnabled ? 'success' : 'info'">
              {{ scope.row.showEnabled ? '开启' : '关闭' }}
            </el-tag>
          </template>
        </el-table-column> -->
      <el-table-column label="操作" width="400" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" class="mini-btn" @click="handleView(scope.row)">查看</el-button>
          <el-button type="primary" size="small" class="mini-btn" :disabled="mainStore.userInfo.id == scope.row.id" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            :type="scope.row.enabled ? 'danger' : 'primary'"
            size="small"
            class="mini-btn"
            :disabled="mainStore.userInfo.id == scope.row.id"
            v-if="mainStore.userInfo.role?.roleType >= 90"
            @click="disableUser(scope.row)"
            >{{ scope.row.enabled ? '停用' : '启用' }}</el-button
          >
          <el-button type="danger" size="small" class="mini-btn" :disabled="mainStore.userInfo.id == scope.row.id" v-if="mainStore.userInfo.role?.roleType >= 90" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>

      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <!-- 添加分页组件 -->

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[13, 20, 50, 100,200]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
   

    <el-dialog v-model="dialogVisible" :title="isView ? '查看账号' : form.id ? '编辑账号' : '添加账号'" width="500px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" style="max-width: 400px">
        <el-form-item label="账号" prop="phone">
          <el-input v-model="form.phone" maxlength="11" placeholder="请输入账号" :disabled="isView" />
        </el-form-item>
        <el-form-item label="授权名称" prop="username">
          <el-input v-model="form.username" placeholder="请输入授权名称" :disabled="isView" />
        </el-form-item>
        
        <el-form-item label="合作属性" prop="roleId" v-if="isView">
          <el-input v-model="form.name" placeholder="请输入授权名称" disabled />
        </el-form-item>
        <el-form-item label="合作属性" prop="roleId" v-else>
          <el-select v-model="form.roleId" placeholder="请选择合作属性" style="width: 100%" @change="handleRoleChange" :disabled="isView">
            <el-option v-for="role in roleList.filter((item) => item.id !== '')" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属账号" prop="parentPhone" v-if="showParentSelect">
          <el-autocomplete
            v-model="form.parentPhone"
            :fetch-suggestions="queryParentSearch"
            placeholder="请输入手机号搜索"
            style="width: 100%"
            @select="handleParentSelect"
            :trigger-on-focus="false"
            :disabled="isView" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isView">
          <el-input v-model="form.password" :placeholder="form.id ? '不填写则不修改密码' : '请输入密码'" />
        </el-form-item>
        <el-form-item label="考试模块">
          <el-switch v-model="form.examEnabled" :disabled="isView" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ isView ? '关闭' : '取消' }}</el-button>
          <el-button v-if="!isView" type="primary" @click="submitForm" :loading="loading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <ViewUserDialog ref="viewDialogRef" :role-list="roleList" />
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import Http from '@/utils/http';
  import ViewUserDialog from '@/components/ViewUserDialog.vue';
  import { useMainStore } from '@/stores/useMain';
  import { imgUrls } from '@/utils/utils';
  const mainStore = useMainStore();
  const filterForm = ref({
    phone: '',
    roleId: '',
    username: '',
  });

  const tableData = ref([]);
  const roleList = ref([]);

  const dialogVisible = ref(false);
  const formRef = ref();
  const form = ref({
    id: '',
    phone: '',
    username: '',
    roleId: '',
    parentPhone: '',
    password: mainStore.morePassword,
    examEnabled: false,
    showEnabled: false,
    superAdminId: '',
    adminId: '',
    areaManagerId: '',
  });
  const viewDialogRef = ref(null);

  // 添加分页相关的响应式变量
  const page = ref(1);
  const pageSize = ref(13);
  const total = ref(0);

  // 新增响应式变量
  const showParentSelect = ref(false);
  const filteredParentUsers = ref([]);
  const selectedRoleType = ref(null);

  // 添加新的响应式变量
  const parentPhoneSearch = ref('');

  // 在script setup部分添加isView变量
  const isView = ref(false);

  onMounted(() => {
    getSubRole();
    getSubuser();
  });

  const rules = {
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
    ],
    username: [{ required: true, message: '请输入账号名称', trigger: 'blur' }],
    roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
    parentPhone: [{ required: true, message: '请选择归属账号', trigger: 'change' }],
    password: [
      {
        validator: (rule, value, callback) => {
          if (!form.value.id && !value) {
            callback(new Error('请输入密码'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
  };

  const getSubRole = async () => {
    const { code, data, msg } = await Http.get({
      url: '/yp_admin/getSubRole',
    });
    if (code != 200) return ElMessage.error(msg);
    roleList.value = [{ id: '', name: '全部' }, ...data];
  };

  const getSubuser = async () => {
    const { code, data, msg } = await Http.get({
      url: '/yp_admin/getSubuser',
      params: {
        ...filterForm.value,
        page: page.value,
        pageSize: pageSize.value,
      },
    });
    if (code != 200) return ElMessage.error(msg);
    tableData.value = data.list;
    total.value = data.total;
  };

  const handleSearch = () => {
    getSubuser();
  };

  // 添加分页处理方法
  const handleSizeChange = (val) => {
    pageSize.value = val;
    page.value = 1; // 切换每页条数时重置为第一页
    getSubuser();
  };

  const handleCurrentChange = (val) => {
    page.value = val;
    getSubuser();
  };

  const resetForm = () => {
    filterForm.value = {
      phone: '',
      roleId: '',
      username: '',
    };
    page.value = 1; // 重置时回到第一页
    handleSearch();
  };

  const handleView = (row) => {
    isView.value = true;
    dialogVisible.value = true;
    form.value = {
      id: row.id,
      phone: row.phone,
      username: row.username,
      roleId: row.role?.id,
      name: row.role?.name,
      parentPhone: row.parentPhone,
      examEnabled: row.examEnabled,
      showEnabled: row.showEnabled,
      superAdminId: row.superAdminId || '',
      adminId: row.adminId || '',
      areaManagerId: row.areaManagerId || '',
    };
   
    

    // 处理父级选择器的显示
    if (row.role) {
      selectedRoleType.value = row.role.roleType;
      filteredParentUsers.value = tableData.value.filter((user) => user.role && user.role.roleType > row.role.roleType && user.id !== row.id);
      showParentSelect.value = filteredParentUsers.value.length > 0;
    }
  };

  const handleEdit = (row) => {
    isView.value = false;
    dialogVisible.value = true;
    form.value = {
      id: row.id,
      phone: row.phone,
      username: row.username,
      roleId: row.role?.id,
      parentPhone: row.parentPhone,
      password: '', // 编辑时不显示密码
      examEnabled: row.examEnabled,
      showEnabled: row.showEnabled,
      superAdminId: row.superAdminId || '',
      adminId: row.adminId || '',
      areaManagerId: row.areaManagerId || '',
    };

    // 处理父级选择器的显示
    if (row.role) {
      selectedRoleType.value = row.role.roleType;
      filteredParentUsers.value = tableData.value.filter((user) => user.role && user.role.roleType > row.role.roleType && user.id !== row.id);
      showParentSelect.value = filteredParentUsers.value.length > 0;
    }
  };

  const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该账号吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const { code, msg } = await Http.post({
            url: '/yp_admin/deleteUser',
            data: { id: row.id },
          });
          if (code === 200) {
            ElMessage.success('删除成功');
            getSubuser(); // 刷新表格数据
          } else {
            ElMessage.error(msg || '删除失败');
          }
        } catch (error) {
          console.error('删除账号失败:', error);
          ElMessage.error('删除失败');
        }
      })
      .catch(() => {
        // 取消删除，不做任何操作
      });
  };

  const handleAdd = () => {
    isView.value = false;
    dialogVisible.value = true;
    form.value = {
      id: '',
      phone: '',
      username: '',
      roleId: '',
      parentPhone: '',
      password: mainStore.morePassword,
      examEnabled: false,
      showEnabled: false,
      superAdminId: '',
      adminId: '',
      areaManagerId: '',
    };
    parentPhoneSearch.value = '';
    showParentSelect.value = false;
    filteredParentUsers.value = [];
  };

  const loading = ref(false);

  const submitForm = async () => {
    if (!formRef.value) return;
    if (loading.value) return;
  
    await formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        try {
          const url = form.value.id ? '/yp_admin/updateUser' : '/yp_admin/addUser';
          // 创建提交数据的副本
          const submitData = { ...form.value };
          // 如果是编辑模式且密码为空，删除密码字段
          if (form.value.id && !submitData.password) {
            delete submitData.password;
          }

          const { code, msg } = await Http.post({
            url,
            data: submitData,
          });
          if (code === 200) {
            ElMessage.success(form.value.id ? '编辑成功' : '添加成功');
            dialogVisible.value = false;
            getSubuser();
          } else {
            ElMessage.error(msg || (form.value.id ? '编辑失败' : '添加失败'));
          }
        } catch (error) {
          console.error(form.value.id ? '编辑账号失败:' : '添加账号失败:', error);
          ElMessage.error(form.value.id ? '编辑失败' : '添加失败');
        } finally {
          loading.value = false;
        }
      }
    });
  };

  // 修改 handleRoleChange 方法
  const handleRoleChange = (roleId) => {
    // 每次切换角色时，先清空所有相关ID
    form.value.superAdminId = '';
    form.value.adminId = '';
    form.value.areaManagerId = '';
    form.value.parentPhone = '';

    const selectedRole = roleList.value.find((role) => role.id === roleId);

    if (selectedRole) {
      selectedRoleType.value = selectedRole.roleType;

      // 筛选可选的归属账号
      filteredParentUsers.value = tableData.value.filter((user) => {
        const isValidParent = user.role && user.role.roleType > selectedRole.roleType && user.id !== form.value.id && user.enabled !== false; // 确保账号是启用状态

        return isValidParent;
      });

      showParentSelect.value = filteredParentUsers.value.length > 0;
    } else {
      showParentSelect.value = false;
      selectedRoleType.value = null;
      filteredParentUsers.value = [];
    }
  };

  // 添加搜索建议方法
  const queryParentSearch = (queryString, callback) => {
  
    const results = queryString
      ? filteredParentUsers.value.filter((user) => {
         
          return user.phone && user.phone.toString().includes(queryString);
        })
      : filteredParentUsers.value;
    
    callback(
      results.map((user) => ({
        value: user.phone,
        phone: user.phone,
        ...user,
      })),
    );
  };

  // 修改选择处理方法
  const handleParentSelect = (item) => {
    form.value.parentPhone = item.phone; // 将选中的手机号填入搜索框

    // handleParentChange(item.id);
  };

  // 修改 handleParentChange 方法
  const handleParentChange = (parentId) => {
    // 先清空所有上级ID
    form.value.superAdminId = '';
    form.value.adminId = '';
    form.value.areaManagerId = '';

    // 找到选中的归属账号用户
    const selectedParent = filteredParentUsers.value.find((user) => user.id === parentId);

    if (selectedParent && selectedParent.role) {
      // 根据归属账号的角色类型设置对应的上级ID
      if (selectedParent.role.roleType == 100) {
        form.value.superAdminId = parentId;
      } else if (selectedParent.role.roleType == 90) {
        form.value.adminId = parentId;
      } else if (selectedParent.role.roleType == 80) {
        form.value.areaManagerId = parentId;
      }
    }
  };

  // 导出账号列表
  const handleDowlist = async () => {
    if (!tableData.value.length) {
      ElMessage.warning('暂无数据可导出');
      return;
    }

    try {
      const res = await Http.get({
        url: '/yp_admin/downloadUserList',
        params: filterForm.value,
      });

      if (res.data) {
        const downloadUrl = imgUrls(res.data);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = '账号列表.xlsx';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success('导出成功');
      } else {
        ElMessage.warning('未找到可下载的文件');
      }
    } catch (error) {
      console.error('导出账号列表失败:', error);
      ElMessage.error('导出失败');
    }
  };

  const disableUser = (row) => {
    ElMessageBox.confirm(`确定要${row.enabled ? '停用' : '启用'}该账号吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const { code, msg } = await Http.post({
        url: '/yp_admin/disableUser',
        data: { id: row.id },
      });
      if (code === 200) {
        ElMessage.success('操作成功');
        getSubuser(); // 刷新表格数据
      } else {
        ElMessage.error(msg || '操作失败');
      }
    });
  };
</script>

<style scoped lang="scss">
:deep(.el-input__wrapper) :deep(.el-input__inner){
  width:50px !important;
}
  .el-form--inline .el-form-item {
    margin-right: 10px !important;
  }
  .el-select,
  .el-input {
    width: 180px;
  }
  .account-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    padding: 20px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .filter-section {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin-bottom: 20px;
    .left {
      flex: 1;
      display: flex;
      align-items: center;

      margin-bottom: 10px;
      .left-item {
        flex: 1;
        display: flex;
        align-items: center;
      }
    }
    .right {
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
      margin-bottom: 10px;
    }
  }

  .el-table {
    width: 100%;
    flex: 1;
  }

  :deep(.el-table__cell) {
    text-align: center;
  }

  :deep(.el-tag) {
    width: 60px;
    text-align: center;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  :deep(.el-form-item) {
    margin: 0;
    display: flex;
    align-items: center;
    flex-shrink: 0;
  }

  :deep(.el-form-item__label) {
    height: 40px;
    line-height: 40px;
    padding-right: 12px;
    white-space: nowrap;
  }

  :deep(.el-form-item__content) {
    display: flex;
    align-items: center;
  }

  :deep(.el-input) {
    width: 200px;
  }

  :deep(.el-input__wrapper) {
    height: 40px;
  }

  :deep(.el-input__inner) {
    height: 40px;
    line-height: 40px;
  }

  :deep(.el-select) {
    width: 160px;
  }

  :deep(.el-select__wrapper) {
    height: 40px;
  }

  :deep(.el-button) {
    height: 40px;
    padding: 0 20px;
  }

  /* 弹框中的表单样式 */
  :deep(.el-dialog__body) {
    padding: 20px 0;
  }

  :deep(.el-dialog .el-form) {
    .el-form-item {
      margin-bottom: 20px;
    }
  }

  .el-form-item:last-child {
    margin-bottom: 0;
  }

  /* 确保筛选区域的表单项间距不受影响 */
  .filter-section :deep(.el-form-item) {
    margin: 0;
  }

  :deep(.el-table) {
    flex: 1;
    min-height: 0;
  }

  :deep(.el-table__body-wrapper) {
    overflow-y: auto; /* 表格内容过多时显示滚动条 */
  }

  :deep(.el-table) .el-button + .el-button {
    margin-left: 8px;
  }

  :deep(.mini-btn) {
    padding: 6px 16px;
    font-size: 12px;
    height: 30px;
    margin: 0 10px;
  }

  .pagination-container {
    padding: 10px 0;
    background-color: #fff;
    z-index: 1;
    
    :deep(.el-pagination) {
      justify-content: flex-end;
      margin-top: 10px;
      
      .el-pagination__jump .el-input {
        width: 50px;  /* 调整前往第X页输入框的宽度 */
        .el-input__inner {
          padding: 0 4px;  /* 调整输入框内边距 */
        }
      }
    }
  }

  /* 添加自动完成组件的样式 */
  :deep(.el-autocomplete) {
    width: 100%;
  }

  :deep(.el-autocomplete-suggestion) {
    width: 100%;
  }
</style>
